package info.cs52.fes.action;

import info.cs52.fes.FesAction;
import info.cs52.fes.data.Meal;
import info.cs52.fes.data.User;
import info.cs52.fes.prolog.Engine;
import info.cs52.fes.prolog.TuPrologEngine;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;

public class DialogueAction extends FesAction {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doIt(req);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doIt(req);
	}

	private void doIt(HttpServletRequest req) {
		history = req.getParameter("history");
		String question = req.getParameter("question");
		String answer = req.getParameter("answer");
		
		Engine engine = new TuPrologEngine();
		User user = SessionUtils.getUser(req);
		if (user.getKnowledgeBase() != null) {
			engine.setUserKnowledgeBase(user.getKnowledgeBase());
		}
		if (question != null && answer != null) {
			String term = engine.process(question, answer, 0.5f);
			user.addKnowledge(term);
			history += StringEscapeUtils.escapeHtml(answer) + ".<br/>";
		}
		
		List<List<String>> recommendedMeals = engine.recommend();
		meals = MealUtils.translate(recommendedMeals);
		
		newQuestion = engine.getQuestion();
		if (newQuestion != null) {
			if (history == null) {
				history = newQuestion + "?<br/>";
			} else {
				history += StringEscapeUtils.escapeHtml(newQuestion) + "?<br/>";
			}
		}
	}

	private List<Meal> meals;
	private String history;
	private String newQuestion;

	public List<Meal> getMeals() {
		return meals;
	}
	
	public String getHistory() {
		return history;
	}
	
	public String getNewQuestion() {
		return newQuestion;
	}
}
